//
//  lanScrollView.swift
//  sinofert_Swift
//
//  Created by enway on 2017/6/23.
//  Copyright © 2017年 enway-wk. All rights reserved.
//

import UIKit


class lanScrollView: UIView,UIScrollViewDelegate {
    
    typealias ianScrollViewSelectBlock = (NSInteger)
    typealias ianScrollViewCurrentIndex = (NSInteger)

    /*
     var slideImagesArray = [Any]()
     var textImageArray = [Any]()
     var ianEcrollViewSelectAction = ianScrollViewSelectBlock()
     var ianCurrentIndex = ianScrollViewCurrentIndex()
     }
     */
    
    var slideImagesArray:NSMutableArray = []//存储图片等地址
    var textImageArray:NSMutableArray = []//文字的数组
    
    var ianEcrollViewSelectAction = ianScrollViewSelectBlock()//图片点击事件
    var ianCurrentIndex = ianScrollViewCurrentIndex()//此时的幻灯片图片序号

    var withoutPageControl:Bool?//是否显示pageControl
    var withoutAutoScroll:Bool?//是否自动滚动
    
    var autoTime:NSNumber?//滚动时间
    var pageControlCurrentPageIndicatorTintColor:UIColor?
    var PageControlPageIndicatorTintColor:UIColor?
    
    var tempPage:NSInteger?
    
    var scrollView:UIScrollView!
    var pageControl:UIPageControl!
    var backView:UIView!
    var nameLabel:UILabel!
    
    
    //加载初始化（必须实现）
    func startLoading() -> Void {
        self.initScrollView()
    }
    //加载初始化并制定初始化图片
    func startLoadingByIndex(index:NSInteger) -> Void {
        self.startLoading()
        tempPage = index
        scrollView.scrollRectToVisible(CGRect.init(x: CGFloat(scrollView.frame.size.width) * CGFloat(index + 1), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: true)
    }
    // scrollView Delegate
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageWith:CGFloat = scrollView.frame.size.width
        
        var page:NSInteger = NSInteger((floor(scrollView.contentOffset.x - pageWith/CGFloat(slideImagesArray.count + 2))/pageWith) + 1)
        page -= 1 // 默认从第二页开始
        pageControl.currentPage = page
        nameLabel.text = textImageArray[pageControl.currentPage] as? String
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageWidth:CGFloat = scrollView.frame.size.width
        var currentPage = floor((scrollView.contentOffset.x - pageWidth / slideImagesArray.count + 2) / pageWidth) + 1
        if
    }
    
    
    
    //private Delegate
    func initScrollView() -> Void {
        if (scrollView != nil) {
            return
        }
        scrollView = UIScrollView()
        scrollView?.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        scrollView?.bounces = false
        scrollView?.isPagingEnabled = true
        scrollView?.delegate = self
        scrollView?.isUserInteractionEnabled = true
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.showsVerticalScrollIndicator = false
        if slideImagesArray.count < 2 {
            scrollView?.isScrollEnabled = false
        }
        self.addSubview(scrollView!)
        
        if (withoutPageControl != nil) {
            backView = UIView()
            backView?.frame = CGRect(x:0, y:0 ,width: self.frame.size.width ,height: 20)
            backView?.backgroundColor = UIColor.black
            backView?.alpha = 0.5
            
            nameLabel = UILabel()
            nameLabel?.frame = CGRect.init(x: 0, y: 0, width: (backView?.frame.size.width)!, height: 20)
            nameLabel?.textColor = UIColor.white
            nameLabel?.textAlignment = NSTextAlignment.center
            nameLabel?.font = UIFont.systemFont(ofSize: 12)
            nameLabel?.text = textImageArray[0] as? String
            
            pageControl = UIPageControl.init(frame: CGRect.init(x: ((scrollView?.frame.size.width)! - 100)/2, y: (scrollView?.frame.size.height)! - 15, width: 100, height: 15))
            

            pageControl?.currentPageIndicatorTintColor = (pageControlCurrentPageIndicatorTintColor != nil) ? (pageControlCurrentPageIndicatorTintColor)! : UIColor.purple
            
            pageControl?.pageIndicatorTintColor = (PageControlPageIndicatorTintColor != nil) ? (PageControlPageIndicatorTintColor)! : UIColor .gray
            
            pageControl?.numberOfPages = slideImagesArray.count
            pageControl?.currentPage = 0
            if slideImagesArray.count < 2 {
                pageControl?.isHidden = true
            }
            
            self.insertSubview(pageControl!, aboveSubview: backView!)
        }
        

        for i in 0..<slideImagesArray.count {
            var slideImage = IanScrollImageView()
            //        slideImage.contentMode = UIViewContentModeScaleAspectFit;
            slideImage.sd_setImage(withURL: URL(string: slideImagesArray[i]), placeholderImage: UIImage(named: " "))
            slideImage.tag = i
            slideImage.frame = CGRect(x: CGFloat(scrollView.frame.size.width * i + scrollView.frame.size.width), y: CGFloat(0), width: CGFloat(scrollView.frame.size.width), height: CGFloat(scrollView.frame.size.height))
            slideImage.addTarget(self, action: #selector(self.ImageClick))
            scrollView.addSubview(slideImage)
            // 首页是第0页,默认从第1页开始的。所以+_scrollView.frame.size.width
        }
        
        // 取数组最后一张图片 放在第0页
        var firstSlideImage = IanScrollImageView()
        //    firstSlideImage.contentMode = UIViewContentModeScaleAspectFit;
        firstSlideImage.sd_setImage(withURL: URL(string: slideImagesArray[slideImagesArray.count - 1]), placeholderImage: UIImage(named: " "))
        firstSlideImage.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(scrollView.frame.size.width), height: CGFloat(scrollView.frame.size.height))
        scrollView.addSubview(firstSlideImage)
        // 取数组的第一张图片 放在最后1页
        var endSlideImage = IanScrollImageView()
        endSlideImage.sd_setImage(withURL: URL(string: slideImagesArray[0]), placeholderImage: UIImage(named: " "))
        endSlideImage.frame = CGRect(x: CGFloat((slideImagesArray.count + 1) * scrollView.frame.size.width), y: CGFloat(0), width: CGFloat(scrollView.frame.size.width), height: CGFloat(scrollView.frame.size.height))
        scrollView.addSubview(endSlideImage)
        scrollView?.contentSize = CGSize(width: ((scrollView?.frame.size.width)! * (CGFloat(slideImagesArray.count) + CGFloat(2))), height: CGFloat(scrollView.frame.size.height))
        //+上第1页和第4页  原理：4-[1-2-3-4]-1
        scrollView?.contentOffset = CGPoint(x: CGFloat(0), y: CGFloat(0))
        scrollView.scrollRectToVisible(CGRect(x: CGFloat((scrollView?.frame.size.width)!), y: CGFloat(0), width: CGFloat((scrollView?.frame.size.width)!), height: CGFloat((scrollView?.frame.size.height)!)), animated: false)
        if !withoutAutoScroll! {
            if !(autoTime != nil) {
                autoTime = Int(4.0) as NSNumber
            }
            var myTimer = Timer(timeInterval: TimeInterval(CFloat(autoTime!)), target: self, selector: #selector(self.runTimePage), userInfo: nil, repeats: true)
            RunLoop.current.add(myTimer, forMode: RunLoopMode.defaultRunLoopMode)
        }
    }
    
    func runTimePage() -> Void {
        var page:NSInteger = pageControl.currentPage
        page += 1
        self.turnPage(page: page)
    }


    func turnPage(page:NSInteger) -> Void {
        tempPage = page
        
        scrollView.scrollRectToVisible(CGRect.init(x: CGFloat(scrollView.frame.size.width) * CGFloat(page + 1), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: true)
    }
    
    func ImageClick(sender:UIImageView) -> Void {
        if self.ianEcrollViewSelectAction != nil {
            ianEcrollViewSelectAction("\(NSInteger(sender.tag))")
            
        }
    }
    
}
